package com.titleevaluation.service;

import com.titleevaluation.entity.Application;
import com.titleevaluation.entity.WorkSummary;
import com.titleevaluation.repository.ApplicationRepository;
import com.titleevaluation.repository.WorkSummaryRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class WorkSummaryService {

    private final WorkSummaryRepository workSummaryRepository;
    private final ApplicationRepository applicationRepository;

    public WorkSummaryService(WorkSummaryRepository workSummaryRepository, ApplicationRepository applicationRepository) {
        this.workSummaryRepository = workSummaryRepository;
        this.applicationRepository = applicationRepository;
    }

    public WorkSummary createOrUpdateWorkSummary(Long applicationId, WorkSummary workSummary) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        workSummary.setApplication(application);
        workSummary.setUpdatedAt(LocalDateTime.now());

        Optional<WorkSummary> existingSummary = workSummaryRepository.findByApplicationId(applicationId);
        if (existingSummary.isPresent()) {
            WorkSummary summaryToUpdate = existingSummary.get();
            summaryToUpdate.setContent(workSummary.getContent());
            return workSummaryRepository.save(summaryToUpdate);
        } else {
            workSummary.setCreatedAt(LocalDateTime.now());
            return workSummaryRepository.save(workSummary);
        }
    }

    public Optional<WorkSummary> getWorkSummaryByApplicationId(Long applicationId) {
        return workSummaryRepository.findByApplicationId(applicationId);
    }
}

